<template>
  <div :class="['login-wrapper', ['', 'login-form-right', 'login-form-left'][direction]]">
    <div class="title">翼飞鸿天无人机智慧城市管理平台</div>
    <el-form
      ref="form"
      size="large"
      :model="form"
      :rules="rules"
      class="login-form"
      @keyup.enter.native="doSubmit">
      <!-- <h4 style="font-size: 25px;">{{ $t('login.title') }}</h4> -->
      <div class="login_header">
          <span class="login_span" @click="cur=true" :class="{active:cur==true}">
          <a >手机号登录</a>
          </span>
          <span class="login_span" @click="cur=false" :class="{active:cur==false}">
          <a >密码登录</a>
          </span>
        </div>

      <el-form-item prop="username">
        <el-input
          clearable
          v-model="form.username"
          prefix-icon="el-icon-user"
          :placeholder="$t('login.username')"/>
      </el-form-item>
      <el-form-item prop="password" v-show="cur==false">
        <el-input
          show-password
          v-model="form.password"
          prefix-icon="el-icon-lock"
          :placeholder="$t('login.password')"/>
      </el-form-item>
      <el-form-item prop="captcha" v-show="cur==true">
        <div class="login-input-group">
          <el-input
            clearable
            v-model="form.captcha"
            prefix-icon="el-icon-_vercode"
            :placeholder="$t('login.captcha')"/>
          <img
            alt=""
            v-if="captcha"
            :src="captcha"
            @click="changeCode"
            class="login-captcha"/>
        </div>
      </el-form-item>
      <el-form-item prop="code" v-show="cur==true">
        <!-- <span class="svg-container">
          <svg-icon icon-class="password" />
        </span> -->
        <el-input ref="code" v-model="form.code" style="width: 315px;" type="text" placeholder="请输入验证码" name="code" abindex="2" maxlength="6" auto-complete="on" @keyup.enter.native="handleLogin" />
        <span class="show-pwd">
          <el-button :loadings="sending" :disabled="sendDisabled" size="small" @click="onSendSms">{{ sendButtonText }}</el-button>
        </span>
      </el-form-item>
      
      <!-- <div class="el-form-item">
        <el-checkbox v-model="form.remember">{{ $t('login.remember') }}</el-checkbox>
      </div> -->
      <div class="el-form-item">
        <el-button
          size="large"
          type="primary"
          class="login-btn"
          :loading="loading"
          @click="doSubmit">
          {{ loading ? $t('login.loading') : $t('login.login') }}
        </el-button>
      </div>
    </el-form>
    <!-- <div class="login-copyright">Copyright © 2018~2023 www.rxthink.cn. All rights reserved.</div> -->
  </div>
</template>

<script>
import setting from '@/config/setting';

import Cookie from "js-cookie";
import moment from "moment";
export default {
  name: 'Login',
  data() {
    return {
      // 登录框方向, 0居中, 1居右, 2居左
      direction: 0,
      // 加载状态
      loading: false,
      // 表单数据
      form: {
        username: '',
        password: '',
        captcha: '',
        key: '',
        remember: true,
        type:true,
        code:''
      },
      // 验证码base64数据
      captcha: '',
      sending: false,
      sendDisabled: false,
      loadings: false,
      timer: 0,
      passwordType: 'password',
      redirect: undefined,

      cur:true,//true代表短信, false代表密码
    };
  },
  computed: {
    // 表单验证规则
    rules() {
      return {
        username: [
          {required: true, message: this.$t('login.username'), type: 'string', trigger: 'blur'}
        ],
        // password: [
        //   {required: true, message: this.$t('login.password'), type: 'string', trigger: 'blur'}
        // ],
        // captcha: [
        //   {required: true, message: this.$t('login.captcha'), type: 'string', trigger: 'blur'}
        // ]
      };
    },
    sendButtonText() {
      if (this.timer === 0) {
        return "发送验证码";
      } else {
        return `${this.timer}秒后重发`;
      }
    }

  },
  mounted() {
    if (setting.takeToken()) {
      this.goHome();
    } else {
      this.changeCode();
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    },
    timer(num) {
      if (num > 0) {
        setTimeout(() => {
          this.timer = --num;
        }, 1000);
      }
    }
  },
  created() {
    const lastSendTime = Cookie.get("last-send-time");
    if (lastSendTime) {
      const timer = 60 - moment().diff(moment(lastSendTime), "seconds");
      this.timer = timer > 0 ? timer : 0;
    }
    const token = this.$route.query._t
    if (token) {
      this.tokenLogin(token)
    }
  },
  methods: {
    /* 提交 */
    doSubmit() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return false;
        }
        if(this.cur == true){
          if(!this.form.code){
              this.$message.error('请输入验证码');
              return false;
            }
            this.form.type = 1;
        }else{
          if(!this.form.password){
              this.$message.error('请输入密码');
              return false;
            }
            this.form.type = 2;
        }
        this.loading = true;
        this.$http.post('/login/login', this.form).then((res) => {
          this.loading = false;
          if (res.data.code === 0) {
            this.$message.success('登录成功');
            this.$store.dispatch('user/setToken', {
              token: 'Bearer ' + res.data.data.access_token,
              remember: this.form.remember
            }).then(() => {
              this.goHome();
            });
          } else {
            this.$message.error(res.data.msg);
            // 重新刷新验证码
            // this.changeCode()
          }
        });
      });
    },
    /* 跳转到首页 */
    goHome() {
      const query = this.$route.query;
      const path = query && query.from ? query.from : '/';
      this.$router.push(path).catch(() => {
      });
    },
    /* 更换图形验证码 */
    changeCode() {
      // 这里演示的验证码是后端返回base64格式的形式
      this.$http.get('/login/captcha').then(res => {
        if (res.data.code === 0) {
          this.captcha = res.data.data.captcha;
          this.form.key = res.data.data.key;
          this.$refs.form.clearValidate();
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch((e) => {
        this.$message.error(e.message);
      });
    },
    onSendSms() {
      this.loginWay = false;

      this.$refs.form.validate((valid) => {
        if (!valid) {
          return false;
        }
        this.sending = true;
        this.$http.post('/login/get_code', this.form).then((res) => {
          if (res.data.code === 0) {
            this.sending = false;
            this.$message.success("短信发送成功，请注意查收");
            Cookie.set("last-send-time", new Date());
              this.timer = 60;
          } else {
            this.$message.error(res.data.msg);
             // 重新刷新验证码
             this.changeCode()
              // console.log(e);
          }
        });
        
      });
    },
    tokenLogin(token) {
      const loading = this.$loading({
        lock: true,
        text: '自动登录中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$http.post('/login/login', {type: 3, token: token}).then((res) => {
        this.loading = false;
        if (res.data.code === 0) {
          this.$store.dispatch('user/setToken', {
            token: 'Bearer ' + res.data.data.access_token,
            remember: this.form.remember
          }).then(() => {
            this.$router.push('/data/basicData');
          });
        } else {
          this.$message.error(res.data.msg);
        }
        loading.close()
      });
    }
  }
}
</script>
<style scoped>
.login_span{
  padding-bottom: 10px;
  border-bottom: 3px solid #687888;
}
.el-button--small{
  color: #ffffff;
    background: #1890ff;
    border-color: #1890ff;
  padding: 13px 15px;
    margin-left: 11px;
}

a{
	color: #bdb0b0;
  margin: 91px;
}
.login_header{
  margin-bottom: 42px;
    text-align: center;
    margin-top: 84px;
}
.login_header span{
	margin-right: 0px;
	cursor: pointer;
}
.Cbody_item{
	border: 0px solid #999;
	overflow: hidden;
}
.active{
    color:#1890ff;
    padding-bottom: 10px;
    border-bottom: 3px solid #1890ff;
}
#app{
  background-color:#fff;
}
</style>
<style scoped>
.title {
  text-align: center;
  font-size: 38px;
  color: #fff;
  margin-top: 100px;
}
/* 背景 */
.login-wrapper {
  padding: 50px 20px;
  position: relative;
  box-sizing: border-box;
  background-image: url("~@/assets/bg.png");
  background-repeat: no-repeat;
  background-size: cover;
  min-height: 100vh;
}

.login-wrapper:before {
  content: "";
  /* background-color: rgba(255, 255, 255, 0.2); */
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

/* 卡片 */
.login-form {
  margin: 0 auto;
  width: 520px;
  height: 415px;
  max-width: 100%;
  padding: 25px 15px;
  position: relative;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.15);
  box-sizing: border-box;
  border-radius: 4px;
  z-index: 2;
  background-image: url("~@/assets/login.png");
  background-size: 100% 100%;

}

.login-form-right .login-form {
  margin: 0 15% 0 auto;
}

.login-form-left .login-form {
  margin: 0 auto 0 15%;
}

.login-form h4 {
  text-align: center;
  margin: 0 0 25px 0;
       margin-top: -86px;
}

.login-form > .el-form-item {
  margin-bottom: 17px;
}
.el-form-item{
  width: 88%;
    margin: auto;
}

/* 验证码 */
.login-input-group {
  display: flex;
  align-items: center;
}

.login-input-group ::v-deep .el-input {
  flex: 1;
}

.login-captcha {
  height: 38px;
  width: 102px;
  margin-left: 10px;
  border-radius: 4px;
  border: 1px solid #DCDFE6;
  text-align: center;
  cursor: pointer;
}

.login-captcha:hover {
  opacity: .75;
}

.login-btn {
  display: block;
  width: 100%;
}

/* 第三方登录图标 */
.login-oauth-icon {
  color: #FFF;
  padding: 5px;
  margin: 0 10px;
  font-size: 18px;
  border-radius: 50%;
  cursor: pointer;
}

/* 底部版权 */
.login-copyright {
  color: #eee;
  padding-top: 20px;
  text-align: center;
  position: relative;
  z-index: 1;
}

/* 响应式 */
@media screen and (min-height: 550px) {
  .login-form {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%);
    margin-top: -220px;
  }

  .login-form-right .login-form,
  .login-form-left .login-form {
    left: auto;
    right: 15%;
    transform: translateX(0);
    margin: -220px auto auto auto;
  }

  .login-form-left .login-form {
    right: auto;
    left: 15%;
  }

  .login-copyright {
    position: absolute;
    bottom: 20px;
    right: 0;
    left: 0;
  }
}

@media screen and (max-width: 768px) {
  .login-form-right .login-form,
  .login-form-left .login-form {
    left: 50%;
    right: auto;
    transform: translateX(-50%);
    margin-right: auto;
  }
}
</style>
